from django.dispatch import receiver
from django.db.models.signals import post_save
from backend.gnsuser.models import GnsUser
from backend.gnsuser.gnsuser import GnsuserAPI
from django.conf import settings
from django.contrib.auth import get_user_model

from logger.createlogger import create_logger

logger = create_logger('GNSUserSignal')

User = get_user_model()

user_api = settings.GNS_USER_API

@receiver(post_save,sender=GnsUser)
def after_gnsuser_save( sender,instance:GnsUser,created,**kwargs):
    user = instance.user

    user_data = {
        'username':user.username,
        'userid':user.id,
        'is_active':user.is_active,
        'is_superuser':user.is_superuser,
        'is_staff':user.is_staff,
        'email':user.email,
    }
    try:
        # if created:
        #     user_api.createItem(app_name='cews',data=user_data)
        # else:
        user_api.updateItem(qrcode=instance.qrcode,app_name='cews',data=user_data)
    except Exception as e:
        print(e)
        logger.critical(f"error when update gnsuser of user {user.username}")
        logger.critical(e)
        
@receiver(post_save,sender=User)
def after_user_save( sender,instance:User,created,**kwargs):
    
    if created:
        return

    ## check user exisit
    
    gnsuser = GnsUser.objects.filter(user_id=instance.id).first() 
    
    if gnsuser:
        user = instance

        user_data = {
            'username':user.username,
            'userid':user.id,
            'is_active':user.is_active,
            'is_superuser':user.is_superuser,
            'is_staff':user.is_staff,
            'email':user.email,
        }   
        try:
            user_api.updateItem(qrcode=gnsuser.qrcode,app_name='cews',data=user_data)
        except Exception as e:
            print(e)
            logger.critical(f"error when after_user_save of user {user.username}")
            logger.critical(e)